//
//  LSTweetStatusController.swift
//  MicroBlog
//
//  Created by lj on 15/9/10.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class LSTweetStatusController: UIViewController, UITextViewDelegate {

    private lazy var keyboardVC: LSEmotionKeyboardController = LSEmotionKeyboardController { [weak self] (emoticon) -> () in

        self?.textView.insertEmoticon(emoticon)
    }

    private var toolbarBottomCons: NSLayoutConstraint?
    private var textViewBottomCons: NSLayoutConstraint?
    private var pictureViewheightCons: NSLayoutConstraint?
    
    // MARK: -监听按钮点击
    @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func tweet() {
        
        let text = textView.emoticonText
        printLog(pictureSelectorVC.pictures.last)
        NetworkTools.sharedNetworkTools.tweetStatus(text, image: pictureSelectorVC.pictures.last).subscribeNext({ (result) -> Void in
            
            SVProgressHUD.showInfoWithStatus("微博发送成功！")
            printLog("tweetSucceed")
            }, error: { (error) -> Void in
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }) { () -> Void in
                self.close()
        }
        
    }
    
    @objc private func selectPicture() {
    
        view.removeConstraint(textViewBottomCons!)
        
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectorVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        
        pictureViewheightCons?.constant =  UIScreen.mainScreen().bounds.height * 0.6
        //关闭键盘
        textView.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc private func switchEmoticonKeyboard() {
        
        textView.resignFirstResponder()
        
        textView.inputView = (textView.inputView == nil) ? keyboardVC.view : nil
        
        textView.becomeFirstResponder()
    }
    
    
    // MARK: - UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
//    func textViewDidChange(textView: UITextView) {
//        placeholderLable.hidden = textView.hasText()
//        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
//    }
    
        
    // MARK: - 生命周期函数
    override func viewDidLoad() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func keyboardChanged(notification:NSNotification) {
        
        //动画曲线
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        UIView.animateWithDuration(duration) { () -> Void in
            //设置动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }

    // MARK: - 界面
    override func loadView() {
    
        view = UIView()
        
        //自动调整ScrollViewInsets，默认为YES
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.whiteColor()
        
        tweetNav()
        tweetToolBar()
        tweetTextView()
        tweetPictureView()
    }

    private func tweetPictureView() {
        
        addChildViewController(pictureSelectorVC)

        view.insertSubview(pictureSelectorVC.view, belowSubview: toolBar)
        
        pictureSelectorVC.view.translatesAutoresizingMaskIntoConstraints = false
        
        let viewsDict = ["picV":pictureSelectorVC.view]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[picV]-0-|", options: [], metrics: nil, views: viewsDict))
        view.addConstraint(NSLayoutConstraint(item: pictureSelectorVC.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
        pictureViewheightCons = NSLayoutConstraint(item: pictureSelectorVC.view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: AnyObject?.None, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 0)
        view.addConstraint(pictureViewheightCons!)
        
        
    }
    
    /// 文本输入框
    private func tweetTextView() {
        view.addSubview(textView)
        
//        textView.text = "刘亚伟JJ只有1CM"
        //自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        
        view.addConstraint(textViewBottomCons!)
        
        textView.addSubview(placeholderLabel)
        placeholderLabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeholderLabel.bounds.size)
        
    }

    
    /// 工具栏
    private func tweetToolBar() {
        
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        //自动布局
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 44))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: UIScreen.mainScreen().bounds.width))
        toolbarBottomCons = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)
        view.addConstraint(toolbarBottomCons!)
        
        
        
        // 定义按钮数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action":"switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        
        // 添加按钮
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    
    /// 导航条
    private func tweetNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "tweet")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        let titleLable = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLable = UILabel(title: LSUserAccountViewModel.sharedUserAccountViewModel.userAccount?.name, color: UIColor.grayColor(), fontSize: 12)
        
        titleView.addSubview(titleLable)
        titleView.addSubview(nameLable)
        
        titleLable.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLable.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
        
    }
    
    //MARK: 懒加载控件
    /// 文本输入框
    private lazy var textView:UITextView = {
    
        let textView = UITextView()
        
        textView.delegate = self
        
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.darkGrayColor()
        
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return textView
    }()
    
    private lazy var placeholderLabel:UILabel = UILabel(title: "刘亚伟JJ只有1CM", color: UIColor.lightGrayColor(), fontSize: 18)
    
    /// 工具条
    private lazy var toolBar = UIToolbar()
    
    private lazy var pictureSelectorVC = LSPictureSelectorController()
    
}
